package com.longder.kindergarten.service.impl;

import com.longder.kindergarten.entity.po.Child;
import com.longder.kindergarten.entity.po.ClassGrade;
import com.longder.kindergarten.repository.ChildRepository;
import com.longder.kindergarten.repository.ClassGradeRepository;
import com.longder.kindergarten.service.ChildrenManageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ChildrenMangeServiceImpl implements ChildrenManageService {

    @Resource
    private ChildRepository childRepository;
    @Resource
    private ClassGradeRepository classGradeRepository;

    /**
     * 添加或修改单个娃
     *
     * @param child
     */
    @Transactional
    @Override
    public void addOrUpdateChild(Child child) {
        // 如果是修改 不允许修改班级
        if(!ObjectUtils.isEmpty(child.getId())){
            Child dbChild = childRepository.getById(child.getId());
            dbChild.setName(child.getName());
            dbChild.setAge(child.getAge());
            dbChild.setGender(child.getGender());
            dbChild.setEmergencyContact(child.getEmergencyContact());
            dbChild.setEmergencyMobile(child.getEmergencyMobile());
            childRepository.save(dbChild);
        }else{
            // 处理班级
            ClassGrade classGrade = classGradeRepository.findById(child.getClassId()).orElseThrow();
            child.setClassGrade(classGrade);
            childRepository.save(child);
        }
    }

    /**
     * 查询某班级下的学生
     *
     * @param classId
     */
    @Override
    public List<Child> listByClassId(Long classId) {
        return childRepository.listByClassId(classId);
    }

    /**
     * 查询单个学生信息
     *
     * @param childId
     * @return
     */
    @Override
    public Child getChild(Long childId) {
        return childRepository.getById(childId);
    }
}
